//获取应用实例
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
var app = getApp();

var util = require('../../utils/util.js');

Page({
  data: { // 参与页面渲染的数据
    getPhoneNumbers: false, //弹出手机号授权框
    MenuUrl:"", //首页中间板块菜单url地址
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    userType: "2",
    logs: [],
    grids: [{
        gridbgURL: "../../img/law.png",
        gridText: "法律咨询",
       clickURL:"../mlcchat/mlcchat?type=1&&chatname=法律咨询"
      },
      {
        gridbgURL: "../../img/BP.png",
        gridText: "BP提交",
        clickURL: "../BPUpload/BPUpload?type=1"
      },
      {
        gridbgURL: "../../img/contract.png",
        gridText: "合同审查",
        clickURL: "../BPUpload/BPUpload?type=2"
      },
      {
        gridbgURL: "../../img/patent.png",
        gridText: "知识产权",
        clickURL: "../mlcchat/mlcchat?type=2&&chatname=知识产权"
      },
      {
        gridbgURL: "../../img/tax.png",
        gridText: "金融财税",
        clickURL: "../mlcchat/mlcchat?type=3&&chatname=金融财税"
      },
      
      {
        gridbgURL: "../../img/gov_fund.png",
        gridText: "政府资助",
        clickURL: "../mlcchat/mlcchat?type=4&&chatname=政府资助"
      },
      {
        gridbgURL: "../../img/all.png",
        gridText: "综合服务",
        clickURL: "../mlcchat/mlcchat?type=5&&chatname=综合服务"
      }
    ],
    navH:0,
    getUser:false

  },

  onLoad: function() {
    let that=this
    if (wx.getStorageSync('userType')){
      this.setData({
        userType: wx.getStorageSync('userType')
      })
    }


    this.setData({
      navH: app.globalData.navHeight
    })


    wx.request({
      url: util.api+"/iim/im/Landing",
      data: {
        token:wx.getStorageSync('token'),
        },
        success: function(res) {
          var tmpsig = res.data;
          console.log("the return of getUserSigByTelephone is:" + tmpsig);
          console.log(res)

          if(!tmpsig.success){
            that.setData({
              getUser:true
            })
          }else{

            that.setData({
              getUser:false
            })

            // that.index(options.type)
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)

          that.setData({
            getUser:true
          })


          return false;
        },
      })
    
  },
  consultChat: function(event) {
    console.log(event);
    var viewDataSet = event.target.dataset;
    var viewText = viewDataSet.text;
    console.log("the viewText is " + viewText);

    wx.getStorage({
      key: 'userSig',
      success: function(res) {
        var userSig = res.data;
        console.log("the userSig get from local storage is " + userSig);
        // check all the variable get from local storage
        // check the variable get from the local storage
        var sentTo = app.globalData.sentTo;
        if ((userSig.length > 0)) {
          wx.navigateTo({
            url: '../mlcchat/mlcchat?sentTo=' + sentTo,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          });
          // end wx.navigateTo
        }else{
          navigateToRegister();
        }

      },
      //the variable is not in local storage
      fail:function(){
        navigateToRegister();
      }

    });
    //end wx.getStorage


  }, //end function consult

onShow:function(){
  
},


formSubmit: function(e) {

  console.log( 'formid'+e.detail.formId)

  if (e.detail.formId != 'the formId is a mock one' && e.detail.formId!='') {
    wx.request({
      url: util.api+"/iim/im/saveFromid",
      data: {
        token:wx.getStorageSync('token'),
        fromid:e.detail.formId
        },
        success: function(res) {
          var tmpsig = res.data;
  
          console.log("the return of getUserSigByTelephone is:" + tmpsig);
          console.log(res)

          if(!tmpsig.success){
          
          }else{
           
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
      })
  }
  




},

    //授权
     loginGin: function(e) {
      console.log('登录')
      let that = this;
      wx.login({
        success: function(res) {
          console.log(res)
          if (res.code) {
            console.log(e)
            that.goLogin(res.code, e.detail.encryptedData, e.detail.iv);
          } else {
            wx.showModal({
              title: '提示',
              content: '获取用户信息超时，请重试',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {

                  that.setData({
                    getUser:true
                  })

                }
              }
            })
          }
        }
      });
    },
    goLogin(code,encryptedData,iv){
      let that=this
      wx.request({
        url: util.api+"/iim/im/onLogin",
        data: {
          code:code,
          encryptedData:encryptedData,
          iv:iv,
        },
        success: function(res) {
          var tmpsig = res.data;

          console.log("the return of getUserSigByTelephone is:" + tmpsig);
          console.log(res);


          console.log(tmpsig)

          if(tmpsig.success){

            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });

          wx.setStorageSync('userId', tmpsig.body.data.id);    // 用户ID
          wx.setStorageSync('token', tmpsig.body.token);
          // wx.setStorageSync('isRegistered', tmpsig.body.data.mobile);
          wx.setStorageSync('loginName', tmpsig.body.data.loginName);
          wx.setStorageSync('userType', tmpsig.body.data.userType);
          app.isPhoneNumber(); //判断是否随机生成手机号
          
          
          
          that.setData({
            getUser:false,
            userType: tmpsig.body.data.userType
          })

          //   wx.switchTab({
          //     url: '../index/index',
          //     success: function (e) {
          //       let page = getCurrentPages().pop();
          //       if (page == undefined || page == null) return;
          //       page.onLoad();
          //   }
          // })
        }

          if(!tmpsig.success){
            wx.showToast({
              title: '登录失败',
              duration: 2000
            });

            that.setData({
              getUser:true
            })
          }
          
        

        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
        complete: function(res) {
          // console.log("the return of consultantRegister complete is:" + res.data);
          // console.log(res);
        } //请求完成后执行的函数
      })
    },
  isphone(e){  //进入子页面前判断是否获取到用户手机号
    let that=this;

    if(that.data.userType=="1"){
      wx.showToast({
        title: "您为咨询客服",
        duration: 2000
      });
    } else {


    // console.log(e.currentTarget.dataset.url)
    that.setData({
      MenuUrl: e.currentTarget.dataset.url
    })
     wx.getStorage({
      key: 'isRegistered',
      success: function(res) {
        //console.log(res.data,'这个是手机号')
          wx.navigateTo({
            url: e.currentTarget.dataset.url,
          })
      },
      fail:function(){
        that.setData({
          getPhoneNumbers: true
        })
        console.log('没有手机号')
      }
    })
    }
    
  },
  getPhoneNumber: function (e) {  // 获取手机号
    let that = this
    wx.checkSession({
      success: function (res) {
        console.log(res, '登录未过期')

        if (e.detail.errMsg === 'getPhoneNumber:ok') {

          // that.setData({
          //   encryptedData1:e.detail.encryptedData,
          //   iv1: e.detail.iv,
          //   getPhoneNumbers:false
          // })

          let token1 = wx.getStorageSync('token')
          wx.request({
            // url: "https://www.cdlpkj.cn/school/a/iim/im/onLogin",
            url: util.api + "/iim/im/decryptPhone",
            data: {
              token: token1,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
            },
            success: function (res) {
              var tmpsig = res.data;
              console.log("the return of getUserSigByTelephone is:" + tmpsig);
              console.log(res);
              console.log(tmpsig)
              if (tmpsig.success) {

                wx.showToast({
                  title: tmpsig.msg,
                  duration: 2000
                });

                wx.setStorageSync('isRegistered', tmpsig.body.mobile);

                that.setData({
                  getUser: false,
                  getPhoneNumbers: true,
                  btnValue: "已经登录，不需要重复登录"
                })
                wx.navigateTo({ //转跳至目标页
                  url: that.data.MenuUrl,
                })
                
                that.setData({
                  getPhoneNumbers: false
                })

              }

              if (!tmpsig.success) {

                if (tmpsig.errorCode == 401) {
                  wx.showToast({
                    title: '请登录',
                    duration: 2000
                  });
                  that.setData({
                    getUser: true,
                    getPhoneNumbers: false
                  })

                } else {
                  wx.showToast({
                    title: '获取失败,请重试',
                    duration: 2000
                  });
                  that.setData({
                    getPhoneNumbers: true,
                    getUser: false,
                  })
                }
              }
            },

            fail: function (resp) {

              wx.showToast({
                title: '请联系管理人员',
                duration: 2000
              });

              console.log("getUserSigByTelephone failed,the response is %o", resp)
              return false;
            },
            complete: function (res) {
              // console.log("the return of consultantRegister complete is:" + res.data);
              // console.log(res);
            } //请求完成后执行的函数
          })

        } else {
          wx.showToast({
            title: '获取手机号失败',
            duration: 2000
          });
          that.setData({
            getPhoneNumbers: false
          })

        }
      },

      fail: function (res) {
        console.log(res, '')
        wx.showToast({
          title: '登录过期了',
          duration: 1000
        });


      }
    })
  },
  UserPhoneCall(){  //拨打服务热线
    wx.makePhoneCall({
      phoneNumber: '400-881-0580'
    })
  }

})
//end Page

//user define function
function navigateToRegister(){
  //please register when local variable is not exist.
  wx.showToast({
    title: '请先注册',
    icon: 'success',
    duration: 2000
  });
  setTimeout(function () {
    console.log("now we go to register page");
    wx.navigateTo({
      url: '../register/register'
    })
  }, 2000);
}
// end function navigateToRegister